package home.fragment;

import static utils.TokenUtils.isLoggedIn;
import static utils.TokenUtils.getToken;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.xfengshopping.MainActivity;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import base.BaseFragment;
import com.example.xfengshopping.R;
import search.Adapter.ProductAdapter;
import search.Product;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.material.tabs.TabLayout;
import LOGIN.login;
import search.SearchResponse;

import java.util.Collections;


public class SearchFragment extends BaseFragment {

    private RecyclerView recyclerView;
    private ProductAdapter productAdapter;
    private List<Product> productList = new ArrayList<>();
    private EditText searchEditText;
    private TextView searchTextView;
    private TabLayout tabLayout;

    private static final String TAG = "SearchFragment";
    private String currentKeyword = "";
    private int currentCategoryId = 0; // 默认分类
    private String currentOrderBy = "default"; // 默认排序
    private int currentPage = 0; // 当前页码
    private boolean isLoading = false; // 防止重复加载
    private int totalPage = 1; // 总页数

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search, container, false);

        // 初始化视图
        initViews(view);
        // 设置监听器
        setupListeners();
        backMListener(view);
        setupScrollListener();
        return view;
    }


    private void setupScrollListener() {
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                if (layoutManager == null) return;

                int visibleItemCount = layoutManager.getChildCount();
                int totalItemCount = layoutManager.getItemCount();
                int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

                // 检查是否滑动到底部且不是正在加载状态
                if (!isLoading && (visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                        && firstVisibleItemPosition >= 0
                        && totalItemCount >= 10 // 确保至少有10个item才触发加载更多
                        && currentPage < totalPage) {

                    isLoading = true;
                    currentPage++;
                    performSearch();

                    // 显示加载中的提示
                    Toast.makeText(getActivity(), "加载中...", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void parseResponseData(String responseData) {
        Log.d(TAG, "原始响应: " + responseData);

        try {
            Gson gson = new Gson();
            SearchResponse response = gson.fromJson(responseData, SearchResponse.class);

            if (response.getResultCode() != 200) {
                handleError(response.getMessage(), response.getResultCode());
                return;
            }

            SearchResponse.Data data = response.getData();
            List<Product> newProducts = data != null ? data.getList() : Collections.emptyList();

            // 更新总页数
            if (data != null) {
                totalPage = data.getTotalPage();
            }

            getActivity().runOnUiThread(() -> {
                if (currentPage == 1) {
                    productList.clear();
                }

                if (!newProducts.isEmpty()) {
                    productList.addAll(newProducts);
                    productAdapter.notifyDataSetChanged();
                }

                isLoading = false; // 加载完成
                updatePaginationInfo(data);
            });

        } catch (Exception e) {
            Log.e(TAG, "解析错误", e);
            getActivity().runOnUiThread(() -> {
                Toast.makeText(getActivity(), "数据解析失败", Toast.LENGTH_SHORT).show();
                isLoading = false; // 加载失败也要重置状态
            });
        }
    }



    private void backMListener(View view) {
        if (view == null) {
            return;
        }

        ImageView backMain = view.findViewById(R.id.back_img);
        if (backMain != null) {
            backMain.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(requireActivity(), MainActivity.class);
                    startActivity(intent);
                }
            });
        }
    }

    private void initViews(View view) {
        recyclerView = view.findViewById(R.id.recyclerView);
        searchEditText = view.findViewById(R.id.search);
        searchTextView = view.findViewById(R.id.search_text_view);
        tabLayout = view.findViewById(R.id.tl_main);

        // 设置RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        productAdapter = new ProductAdapter(productList);
        recyclerView.setAdapter(productAdapter);

    }



    private void setupListeners() {
        // 搜索按钮点击事件
        searchTextView.setOnClickListener(v -> {
            currentKeyword = searchEditText.getText().toString().trim();
            currentPage = 1; // 重置页码
            performSearch();
        });

        // Tab选择监听
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()) {
                    case 0: // 推荐
                        currentOrderBy = "";
                        break;
                    case 1: // 新品
                        currentOrderBy = "new";
                        break;
                    case 2: // 价格
                        currentOrderBy = "price";
                        break;
                }
                performSearch();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}

            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        if (!isLoggedIn(mContext)) {
            redirectToLogin();
            return;
        }

        verifyTokenBeforeSearch();
    }

    private void verifyTokenBeforeSearch() {
        String token = getToken(mContext);
        if (isTokenExpired(token)) {
            redirectToLogin();
        } else {
            // 初始加载推荐商品
            performSearch();
        }
    }

    private void performSearch() {
        searchProducts(currentKeyword, currentCategoryId, currentOrderBy, currentPage);
    }

    private boolean isTokenExpired(String token) {
        // 实现token过期检查逻辑
        // 简单实现：检查token是否存在且长度合理
        return token == null || token.length() < 10;
    }

    private void redirectToLogin() {
        Toast.makeText(mContext, "请先登录", Toast.LENGTH_SHORT).show();
        new Handler().postDelayed(() -> {
            Intent intent = new Intent(mContext, login.class);
            Log.e("skip","跳转到登录");
            // 添加标志清除任务栈
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        }, 1000);
    }

    private void searchProducts(String keyword, int goodsCategoryId, String orderBy, int pageNumber) {
        String token = getToken(mContext);
        OkHttpClient client = new OkHttpClient();

        HttpUrl url = HttpUrl.parse("http://47.99.134.126:28019/api/v1/search").newBuilder()
                //校内"http://115.158.64.84:28019/api/v1/user/login"
                .addQueryParameter("keyword", keyword)
                .addQueryParameter("goodsCategoryId", String.valueOf(goodsCategoryId))//String.valueOf(goodsCategoryId)
                .addQueryParameter("orderBy", orderBy)
                .addQueryParameter("pageNumber", String.valueOf(pageNumber))
                .build();

        Request request = new Request.Builder()
                .url(url)
                .addHeader("token", token)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                getActivity().runOnUiThread(() -> {
                    Toast.makeText(getActivity(), "请求失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    parseResponseData(responseData);
                } else {
                    getActivity().runOnUiThread(() -> {
                        Toast.makeText(getActivity(), "请求失败: " + response.message(), Toast.LENGTH_SHORT).show();
                    });
                }
            }
        });
    }


    private void setupLoadMoreListener(int totalPage) {
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int visibleItemCount = layoutManager.getChildCount();
                int totalItemCount = layoutManager.getItemCount();
                int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

                if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                        && firstVisibleItemPosition >= 0
                        && totalItemCount >= productAdapter.getItemCount()
                        && currentPage < totalPage) {
                    currentPage++;
                    performSearch();
                }
            }
        });
    }


    private void handleError(String message, int resultCode) {
        getActivity().runOnUiThread(() -> {
            Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();

            if (resultCode == 401 || resultCode == 403 || resultCode == 416) {
                new Handler().postDelayed(() -> {
                    Intent intent = new Intent(getActivity(), login.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                }, 1000);
            }
        });
    }

    /*private void updateEmptyState() {
        if (emptyView != null && recyclerView != null) {
            boolean isEmpty = productList.isEmpty();
            emptyView.setVisibility(isEmpty ? View.VISIBLE : View.GONE);
            recyclerView.setVisibility(isEmpty ? View.GONE : View.VISIBLE);

            if (isEmpty) {
                emptyView.setText("暂无商品数据");
            }
        }
    }*/

    private void updatePaginationInfo(SearchResponse.Data data) {
        if (data != null) {
            String info = String.format("第%d页/共%d页 总数:%d",
                    data.getCurrPage() + 1,
                    data.getTotalPage(),
                    data.getTotalCount());
            Log.d(TAG, "分页信息: " + info);
        }
    }
}
